package com.example.teemor.es_demo.service;

import com.example.teemor.es_demo.entity.User;
import com.example.teemor.es_demo.repository.jpa.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    /**
     * 创建用户
     */
    @Transactional
    public User createUser(User user) {
        log.info("Creating user: {}", user.getUsername());
        
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在: " + user.getUsername());
        }
        
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(user.getEmail())) {
            throw new RuntimeException("邮箱已存在: " + user.getEmail());
        }
        
        return userRepository.save(user);
    }

    /**
     * 根据ID获取用户
     */
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    /**
     * 根据用户名获取用户
     */
    public Optional<User> getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    /**
     * 根据邮箱获取用户
     */
    public Optional<User> getUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    /**
     * 根据用户名或邮箱获取用户
     */
    public Optional<User> getUserByUsernameOrEmail(String usernameOrEmail) {
        return userRepository.findByUsernameOrEmail(usernameOrEmail);
    }

    /**
     * 更新用户信息
     */
    @Transactional
    public User updateUser(Long id, User userDetails) {
        log.info("Updating user: {}", id);
        
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + id));
        
        // 更新用户信息
        if (StringUtils.hasText(userDetails.getUsername()) && 
            !user.getUsername().equals(userDetails.getUsername())) {
            if (userRepository.existsByUsername(userDetails.getUsername())) {
                throw new RuntimeException("用户名已存在: " + userDetails.getUsername());
            }
            user.setUsername(userDetails.getUsername());
        }
        
        if (StringUtils.hasText(userDetails.getEmail()) && 
            !user.getEmail().equals(userDetails.getEmail())) {
            if (userRepository.existsByEmail(userDetails.getEmail())) {
                throw new RuntimeException("邮箱已存在: " + userDetails.getEmail());
            }
            user.setEmail(userDetails.getEmail());
        }
        
        if (StringUtils.hasText(userDetails.getPhone())) {
            user.setPhone(userDetails.getPhone());
        }
        
        if (StringUtils.hasText(userDetails.getAddress())) {
            user.setAddress(userDetails.getAddress());
        }
        
        return userRepository.save(user);
    }

    /**
     * 删除用户
     */
    @Transactional
    public void deleteUser(Long id) {
        log.info("Deleting user: {}", id);
        
        if (!userRepository.existsById(id)) {
            throw new RuntimeException("用户不存在: " + id);
        }
        
        userRepository.deleteById(id);
    }

    /**
     * 获取所有用户（分页）
     */
    public Page<User> getAllUsers(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    /**
     * 搜索用户
     */
    public List<User> searchUsers(String keyword) {
        if (!StringUtils.hasText(keyword)) {
            return List.of();
        }
        return userRepository.searchUsers(keyword);
    }

    /**
     * 检查用户名是否可用
     */
    public boolean isUsernameAvailable(String username) {
        return !userRepository.existsByUsername(username);
    }

    /**
     * 检查邮箱是否可用
     */
    public boolean isEmailAvailable(String email) {
        return !userRepository.existsByEmail(email);
    }

    /**
     * 获取用户总数
     */
    public long getUserCount() {
        return userRepository.count();
    }

    /**
     * 获取用户统计信息
     */
    public Map<String, Object> getUserStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalUsers", userRepository.count());
        stats.put("activeUsers", userRepository.countByStatus(User.UserStatus.ACTIVE));
        stats.put("inactiveUsers", userRepository.countByStatus(User.UserStatus.INACTIVE));
        return stats;
    }

    /**
     * 根据关键词搜索用户
     */
    public Page<User> searchByKeyword(String keyword, Pageable pageable) {
        if (!StringUtils.hasText(keyword)) {
            return userRepository.findAll(pageable);
        }
        return userRepository.searchUsersByKeyword(keyword, pageable);
    }

    /**
     * 批量更新用户状态
     */
    @Transactional
    public void batchUpdateStatus(List<Long> userIds, User.UserStatus status) {
        log.info("Batch updating user status: {} users to {}", userIds.size(), status);
        userRepository.batchUpdateStatus(userIds, status);
    }

    /**
     * 获取活跃用户列表
     */
    public List<User> getActiveUsers() {
        return userRepository.findByStatus(User.UserStatus.ACTIVE);
    }
}